package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.MemberElderDto;
import com.zzyl.entity.Elder;
import com.zzyl.entity.MemberElder;
import com.zzyl.exception.BusinessException;
import com.zzyl.mapper.ElderMapper;
import com.zzyl.mapper.MemberElderMapper;
import com.zzyl.service.MemberElderService;
import com.zzyl.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MemberElderServiceImpl extends ServiceImpl<MemberElderMapper, MemberElder> implements MemberElderService {

    @Autowired
    private ElderMapper elderMapper;

    //新增客户老人关联记录
    @Override
    public void saveMemberElder(MemberElderDto memberElderDto) {
        //1. 查询老人信息是否存在
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo, memberElderDto.getIdCard())
                .eq(Elder::getName, memberElderDto.getName())
                .between(Elder::getStatus, 1, 4);//0：禁用，1:启用  2:请假 3:退住中 4入住中 5已退住
        Elder elder = elderMapper.selectOne(wrapper);
        if (elder == null) {
            throw new BusinessException("绑定失败,老人信息不存在");
        }

        //2. 保存绑定关系
        MemberElder memberElder = BeanUtil.copyProperties(memberElderDto, MemberElder.class);
        memberElder.setMemberId(UserThreadLocal.getUserId());
        memberElder.setElderId(elder.getId());
        try {
            getBaseMapper().insert(memberElder);
        } catch (Exception e) {
            throw new BusinessException("绑定失败,已绑定过此信息");
        }
    }

    @Override
    public PageResponse<MemberElder> findByPage(Long memberId, Long elderId, Integer pageNum, Integer pageSize) {
        Page<MemberElder> page = new Page<>(pageNum,pageSize);

        page = getBaseMapper().findByPage(page,memberId, elderId);

        return new PageResponse<>(page);
    }
}
